<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.siteName"
        placeholder="输入站址名称查询"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.siteCode"
        placeholder="输入站址编码查询"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.siteMaintanceID"
        placeholder="输入运维ID查询"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />

      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        查询
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        @click="openLoad"
      >
        导入运维巡检人员
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      style="width: 100%"
      @sort-change="sortChange"
    >
      <el-table-column
        label="Id"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{ row }">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="创建时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="站址名称" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.siteName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="站址编码" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.siteCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属省市区" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.province + row.city + row.area }}</span>
        </template>
      </el-table-column>
      <el-table-column label="乡镇" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.town }}</span>
        </template>
      </el-table-column>
      <el-table-column label="乡镇代码" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.townCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="运维ID" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.siteMaintanceid }}</span>
        </template>
      </el-table-column>
      <el-table-column label="运维商共享情况" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.siteOperatorShare }}</span>
        </template>
      </el-table-column>
      <el-table-column label="经/纬度" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.siteLongitude + "/" + row.siteLatitude }}</span>
        </template>
      </el-table-column>
      <el-table-column label="机房(动环)维护人员" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.siteMaintainer }}</span>
        </template>
      </el-table-column>
      <el-table-column label="机房类型" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.machineroomType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="站类型" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.siteType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="站址中机柜数量" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.cabinetNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="170">
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button
            v-if="row.status != 'deleted'"
            size="mini"
            type="danger"
            @click="handleDelete(row, $index)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page-sizes="[20]"
      :page.sync="listQuery.currentPage"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :width="'800px'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="dataForm"
        :inline="true"
        :rules="rules"
        :model="temp"
        label-width="140px"
        style="margin-left: 20px"
      >
        <el-form-item label="站址名称" prop="siteName">
          <el-input
            v-model="temp.siteName"
            :disabled="dialogStatus === 'create' ? false : true"
          />
        </el-form-item>
        <el-form-item label="站址编码" prop="siteCode">
          <el-input v-model="temp.siteCode" />
        </el-form-item>
        <el-form-item label="乡镇">
          <el-input v-model="temp.town" />
        </el-form-item>
        <el-form-item label="乡镇代码">
          <el-input v-model="temp.townCode" />
        </el-form-item>
        <el-form-item label="运维ID">
          <el-input
            v-model="temp.siteMaintanceid"
            :disabled="dialogStatus === 'create' ? false : true"
          />
        </el-form-item>
        <el-form-item label="经度">
          <el-input v-model="temp.siteLongitude" />
        </el-form-item>
        <el-form-item label="纬度">
          <el-input v-model="temp.siteLatitude" />
        </el-form-item>
        <el-form-item label="机房类型">
          <el-input v-model="temp.machineroomType" />
        </el-form-item>
        <el-form-item label="站类型">
          <el-input v-model="temp.siteType" />
        </el-form-item>
        <el-form-item label="站址中机柜数量">
          <el-input v-model="temp.cabinetNumber" />
        </el-form-item>
        <el-form-item label="运维商共享情况">
          <el-input v-model="temp.siteOperatorShare" />
        </el-form-item>
        <el-form-item label="指定巡检员登录名">
          <el-input v-model="temp.inspectorLoginName" />
        </el-form-item>
        <el-form-item label="省市区">
          <el-cascader
            v-model="temp.addressArray"
            :options="addressOptions"
            placeholder="请选择"
            @change="onAddress"
          />
        </el-form-item>
        <el-form-item label="机房(动环)维护人员">
          <el-input v-model="temp.siteMaintainer" />
        </el-form-item>
        <el-form-item label="机房(动环)维护人员组登录名">
          <el-input v-model="temp.maintancerGroup" />
        </el-form-item>
        <el-form-item label="指定巡检员姓名">
          <el-input v-model="temp.inspectorName" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 关闭 </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          提交
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      v-loading="loading"
      title="导入运维巡检人员"
      :visible.sync="dialogLoadVisible"
      :width="'800px'"
      element-loading-text="正在导入中，请不要做其他操作，也不要关闭和刷新页面"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-upload
        v-if="dialogLoadVisible"
        ref="upload"
        :headers="headers"
        :action="actionUrl"
        :auto-upload="false"
        :on-success="onUploadSuccess"
        :limit="1"
        name="filename"
      >
        <el-button
          slot="trigger"
          size="small"
          type="primary"
        >选取文件</el-button>
        <el-button
          style="margin-left: 10px"
          size="small"
          type="success"
          @click="submitUpload"
        >上传到服务器</el-button>
        <el-button
          style="margin-left: 10px"
          size="small"
        ><a
          href="Site_ImportMaintainer-模板.xlsx"
          download
        >下载模板</a></el-button>
      </el-upload>

      <div slot="footer" class="dialog-footer" style="margin-top: 20px">
        <el-input
          v-model="voBatch.successMsg"
          type="textarea"
          :readonly="true"
          :autosize="{ minRows: 1, maxRows: 4 }"
          placeholder="成功导入条数"
        />
        <el-input
          v-model="voBatch.failMsg"
          style="margin-top: 10px"
          :readonly="true"
          type="textarea"
          :autosize="{ minRows: 1, maxRows: 4 }"
          placeholder="未功导入条数"
        />
        <el-input
          v-model="voBatch.errorMsg"
          style="margin-top: 10px"
          :readonly="true"
          type="textarea"
          :disabled="false"
          :autosize="{ minRows: 4, maxRows: 4 }"
          placeholder="未成功导入信息"
        />
        <el-button style="margin-top: 10px" @click="dialogLoadVisible = false">
          关闭
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchList,
  createArticle,
  updateArticle,
  deleteArticle,
} from '@/api/site'
import waves from '@/directive/waves'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'

const sexs = [
  { key: '男', display_name: '男' },
  { key: '女', display_name: '女' },
]

export default {
  name: 'Polling',
  components: { Pagination },
  directives: { waves },
  filters: {},
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      voBatch: {},
      loading: false,
      listQuery: {
        currentPage: 1,
      },
      sexs,
      temp: {},
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加',
      },
      rules: {
        siteName: [{ required: true, message: '必填项', trigger: 'blur' }],
        siteCode: [{ required: true, message: '必填项', trigger: 'blur' }],
      },
      dialogLoadVisible: false,
      actionUrl: '',
      headers: {
        Authorization: getToken(),
      },
    }
  },
  computed: {
    ...mapGetters(['addressOptions', 'loginName']),
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then((response) => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {}
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createArticle(this.temp).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.notifyMessage('创建成功')
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.addressArray = [row.province, row.city, row.area]
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateArticle(tempData).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.notifyMessage('保存成功')
          })
        }
      })
    },
    notifyMessage(info) {
      this.$notify({
        title: info,
        type: 'success',
        duration: 2000,
      })
    },
    handleDelete(row, index) {
      deleteArticle({ siteMaintanceid: row.siteMaintanceid }).then(() => {
        this.getList()
        this.notifyMessage('删除成功')
      })
    },
    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    onAddress(val) {
      if (!val) {
        return
      }
      this.temp.province = val[0] || ''
      this.temp.city = val[1] || ''
      this.temp.area = val[2] || ''
    },
    openLoad() {
      this.dialogLoadVisible = true
      this.voBatch = {}
    },
    submitUpload() {
      this.$nextTick(() => {
        this.actionUrl = `${process.env.VUE_APP_BASE_API}/site/batchImportSiteMaintainer?loginName=${this.loginName}`
      })
      setTimeout(() => {
        this.$refs.upload.submit()
        this.loading = true
      }, 0)
    },
    onUploadSuccess(res) {
      this.$refs.upload.clearFiles() // 调用element官方的方法
      if (res.code === 200) {
        // console.log("res.data" + res.data);
        this.voBatch = res.data
        this.loading = false
        this.getList()
        this.notifyMessage('导入结束')
      }
    },

  },
}
</script>
<style>
</style>
